package com.nf.health.app.activity.global;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.nf.health.app.Constants;
import com.nf.health.app.MyApplication;
import com.nf.health.app.R;
import com.nf.health.app.intervention_details.activity.HealthSurveyActivity;
import com.nf.health.app.homepage.activity.RiskEvaluationActivity;
import com.nf.health.app.homepage.activity.SystemSchemeActivity;
import com.nf.health.app.datamain.activity.TemperatureDataActivity;
import com.nf.health.app.datamain.activity.UrineTestActivity;
import com.nf.health.app.activity.doctor_advice.activity.MyDocAdviceActivity;
import com.nf.health.app.activity.ecg.EcgHistoryActivity;
import com.nf.health.app.activity.my.MyPersonalDoctorActivity;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.bodyfat.BodyFatDataNewActivity;
import com.nf.health.app.core.DialogOnitem;
import com.nf.health.app.customview.BottomSslideDialog;
import com.nf.health.app.customview.CustomShareBoard;
import com.nf.health.app.datamain.activity.BloodOxygenActivity;
import com.nf.health.app.datamain.activity.BloodPressureActivity;
import com.nf.health.app.datamain.activity.BloodSugarDataActivity;
import com.nf.health.app.datamain.activity.HealthyBraceletActivity;
import com.nf.health.app.healthbank.MyHealthBankDetailActivity;
import com.nf.health.app.healthbank.MyHealthyBankActivity;
import com.nf.health.app.healthstate.activity.HealthStateActivity;
import com.nf.health.app.homepage.activity.DoctorDetectionActivity;
import com.nf.health.app.homepage.activity.HealthSelfTestingActivity;
import com.nf.health.app.http.Apis;
import com.nf.health.app.inquiry.activity.FastInquiryActivity;
import com.nf.health.app.inquiry.docdetail.DocDetailActivity;

import com.nf.health.app.mine.activity.FeedbackActivity;
import com.nf.health.app.mine.activity.HealthSchemeActivity;
import com.nf.health.app.mine.activity.MyIntegrationActivity;
import com.nf.health.app.mine.activity.MyhealthActivity;
import com.nf.health.app.mine.activity.SchemeActivity;
import com.nf.health.app.myfamily.activity.MyFamilyActivity;
import com.nf.health.app.sweat.activity.SweatAnalyzerActivity;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.DateUtil;
import com.nf.health.app.utils.SharePlatform;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author Ian
 * @ClassName: WebViewActivity
 * @Description:网页版显示器
 * @date 2015-11-4 上午11:04:54
 */

public class WebViewActivity extends BaseActivity {
    public static final String KEY_URL = "httpUrl";
    public static final String KEY_TITLE = "title";
    public static final String KEY_IMAGE = "img";
    public static final String KEY_IS_SHARE = "share";
    public static final String KEY_SHARE_CONTENT = "shareContent";

    private final UMSocialService mController = UMServiceFactory
            .getUMSocialService(Constants.DESCRIPTOR);
    String id, time;

    @Bind(R.id.ll_content)
    LinearLayout llContent;
    private WebView webview;
    ImageView titlebar_right_view;
    String docid, title, imgurl, content, httpUrl, image;
    boolean isshare;

    String[] reportArr;//分享 收藏页面
    /**
     * 标记收藏与否
     */
    boolean isstore;
    Bitmap bm;
    //	private VideoView videoview;
    private View rl_video;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        httpUrl = getIntent().getStringExtra(KEY_URL);
        title = getIntent().getStringExtra(KEY_TITLE);
        content = getIntent().getStringExtra(KEY_SHARE_CONTENT);
        image = getIntent().getStringExtra(KEY_IMAGE);
        isshare = getIntent().getBooleanExtra(KEY_IS_SHARE, false);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_doctor_advice_detail);
        ButterKnife.bind(this);

        initWebView();
        // 配置需要分享的相关平台
//        configPlatforms();
//        // 设置分享的内容
//        setShareContent();

        if (TextUtils.isEmpty(docid)) {
        } else {
            provider.requestCollection(docid, "ifCollection");//判断是否收藏请求
        }
    }
    private void setShareContent() {
        // 配置SSO
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        UMImage umImage;
        if (TextUtils.isEmpty(image) || image == null) {//判断分享文章中的第一张图片是否为空
            umImage = new UMImage(this, R.mipmap.ic_logo);//赋值默认logo
        } else {
            umImage = new UMImage(this, image);
        }
        String targetUrl = httpUrl;
        String content1 = content;
        // 微信分享必须设置targetURL，需要为http链接格式
        // 微信朋友圈只能显示title，并且过长会被微信截取部分内容
        WeiXinShareContent weixinContent = new WeiXinShareContent();
        weixinContent.setShareContent(content1);
        weixinContent.setTitle(title);
        weixinContent.setTargetUrl(targetUrl);
        weixinContent.setShareMedia(umImage);
        mController.setShareMedia(weixinContent);

        // 设置朋友圈分享的内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent(content1);
        circleMedia.setTitle(title);
        circleMedia.setShareMedia(umImage);
        circleMedia.setTargetUrl(targetUrl);
        mController.setShareMedia(circleMedia);

        QQShareContent qqShareContent = new QQShareContent();
        qqShareContent.setShareContent(content1);
        qqShareContent.setTitle(title);
        qqShareContent.setShareMedia(umImage);
        qqShareContent.setTargetUrl(targetUrl);
        mController.setShareMedia(qqShareContent);
        // 设置QQ空间分享内容
        QZoneShareContent qzone = new QZoneShareContent();
        qzone.setTargetUrl(targetUrl);
        qzone.setShareContent(content1);
        qzone.setTitle(title);
        qzone.setShareMedia(umImage);
        mController.setShareMedia(qzone);
        //新浪微博、腾讯微博及豆瓣的跳转链接只能设置在分享文字之中，以http形式传递即可，人人网可以单独设置跳转链接，方法为：
        SinaShareContent sinaContent = new SinaShareContent();
        sinaContent.setShareContent(title + httpUrl);
        //		sinaContent.setTitle(title);
        sinaContent.setShareImage(umImage);
        mController.setShareMedia(sinaContent);
    }


    private void configPlatforms() {
        // 添加新浪SSO授权
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        SharePlatform.addQQ_QZonePlatform(this);
        SharePlatform.addWXPlatform(this);
    }

    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        webview = new WebView(MyApplication.getInstance());
        llContent.addView(webview);
        WebSettings webSettings = webview.getSettings();
        webSettings.setBuiltInZoomControls(false);//屏幕缩放控件显示
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);//屏幕缩放
        webSettings.setLightTouchEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setDomStorageEnabled(true);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webview.addJavascriptInterface(this, "question");
        }

     
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.contains("clickquestion")) {
                    //clickquestion://click_question?id=285?time=2016-05-10
                    String[] para = url.split("\\?");
                    String id = para[1].split("=")[1];
                    String time = para[2].split("=")[1];

                    Date t1 = DateUtil.string2Date(time, "yyyy-MM-dd");

                    Date t2 = DateUtil.string2Date(DateUtil.date2yyyyMMdd(new Date()), "yyyy-MM-dd");

                    if (t1.getTime() > t2.getTime()) {//大于今天的

                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", id);
                        bundle.putString("type", "2");
                        ActivityUtils.showActivity(WebViewActivity.this, HealthSurveyActivity.class, bundle);
                    }

                } else if (url.contains("clickscheme")) {
                    String id = url.replace("clickscheme://click_scheme?id=", "");
                    Bundle bundle = new Bundle();
                    bundle.putString("id", id);
                    ActivityUtils.showActivity(WebViewActivity.this, HealthSchemeActivity.class, bundle);
                } else if (url.equals("nfau://OPEN_1")) {//快速问诊
                    ActivityUtils.showActivity(WebViewActivity.this, FastInquiryActivity.class);

                } else if (url.equals("nfau://OPEN_2")) {//健康状态
                    ActivityUtils.showActivity(WebViewActivity.this, HealthStateActivity.class);

                } else if (url.equals("nfau://OPEN_3")) {//查找医生

                } else if (url.equals("nfau://OPEN_4")) {//健康自测
                    ActivityUtils.showActivity(WebViewActivity.this, HealthSelfTestingActivity.class);

                } else if (url.equals("nfau://OPEN_5")) {//数据检测

                    showToast("数据检测");

                } else if (url.equals("nfau://OPEN_6")) {//电商

                    ActivityUtils.showActivity(WebViewActivity.this, MyShopStoreActivity.class);

                } else if (url.equals("nfau://OPEN_7")) {//添加方案

                    ActivityUtils.showActivity(WebViewActivity.this, SystemSchemeActivity.class);

                } else if (url.equals("nfau://OPEN_8")) {//我的方案

                    ActivityUtils.showActivity(WebViewActivity.this, SchemeActivity.class);

                } else if (url.equals("nfau://OPEN_9")) {//我的私人医生

                    ActivityUtils.showActivity(WebViewActivity.this, MyPersonalDoctorActivity.class);

                } else if (url.equals("nfau://OPEN_10")) {//我的健康助手

                    ActivityUtils.showActivity(WebViewActivity.this, MyhealthActivity.class);

                } else if (url.equals("nfau://OPEN_11")) {//我的健康银行
                    ActivityUtils.showActivity(WebViewActivity.this, MyHealthyBankActivity.class);

                } else if (url.equals("nfau://OPEN_12")) {//我的积分

                    ActivityUtils.showActivity(WebViewActivity.this, MyIntegrationActivity.class);

                } else if (url.equals("nfau://OPEN_13")) {//我的家人

                    ActivityUtils.showActivity(WebViewActivity.this, MyFamilyActivity.class);

                } else if (url.equals("nfau://OPEN_14")) {//我的医嘱

                    ActivityUtils.showActivity(WebViewActivity.this, MyDocAdviceActivity.class);

                } else if (url.equals("nfau://OPEN_15")) {//意见反馈

                    ActivityUtils.showActivity(WebViewActivity.this, FeedbackActivity.class);

                } else if (url.contains("nfau://ADDSCORE_")) {//添加积分

                    String score = url.replaceAll("nfau://ADDSCORE_", "");
                    provider.requestZdyAddScore(score, "score");

                }
//                else if(url.contains("nfau://OPEN_1_")) {//快速问诊+id
//
//                    showToast("快速问诊" + url.replaceAll("nfau://OPEN_1_", ""));
//
//                }else if(url.contains("nfau://OPEN_2_")) {//健康状态+id
//
//                    showToast("健康状态" + url.replaceAll("nfau://OPEN_2_", ""));
//
//                }
                else if (url.contains("nfau://OPEN_3_")) {//查找医生+id

                    Bundle bundle = new Bundle();
                    bundle.putString(DocDetailActivity.DOCTORID, url.replaceAll("nfau://OPEN_3_", ""));
                    ActivityUtils.showActivity(WebViewActivity.this, DocDetailActivity.class, bundle);

                } else if (url.contains("nfau://OPEN_4_")) {//健康自测+id
                    String var = url.replaceAll("nfau://OPEN_4_", "");
                    if (var.equals("1")) {
                        ActivityUtils.showActivity(WebViewActivity.this, DoctorDetectionActivity.class);//中医体检
                    } else {
                        ActivityUtils.showActivity(WebViewActivity.this, RiskEvaluationActivity.class);//风险评估
                    }

                } else if (url.contains("nfau://OPEN_5_")) {//数据检测+id
                    if (!Util.checkBluetoothAvailable()){
                        showToast("手机不支持蓝牙4.3");
                        return false;
                    }
//                    1 血糖 2 血压 3 尿检 4 体重 5 手环 6 汗液 7 温度 8血氧 9 心电
                    String var = url.replaceAll("nfau://OPEN_5_", "");

                    if (var.equals("1")) {
                        //跳到血糖数据
                        ActivityUtils.showActivity(WebViewActivity.this, BloodSugarDataActivity.class);
                    } else if (var.equals("2")) {
                        //跳到血压数据
                        ActivityUtils.showActivity(WebViewActivity.this, BloodPressureActivity.class);
                    } else if (var.equals("3")) {
                        //跳到尿检数据
                        ActivityUtils.showActivity(WebViewActivity.this, UrineTestActivity.class);
                    } else if (var.equals("4")) {
                        //跳到体脂数据
                        ActivityUtils.showActivity(WebViewActivity.this, BodyFatDataNewActivity.class); //新的体脂测量界面
                    } else if (var.equals("5")) {
                        //跳到手环数据
                        ActivityUtils.showActivity(WebViewActivity.this, HealthyBraceletActivity.class);
                    } else if (var.equals("6")) {
                        //跳到汗液仪数据
                        ActivityUtils.showActivity(WebViewActivity.this, SweatAnalyzerActivity.class);
                    } else if (var.equals("7")) {
                        //跳到体温数据
                        ActivityUtils.showActivity(WebViewActivity.this, TemperatureDataActivity.class);
                    } else if (var.equals("8")) {
                        //跳到血氧数据
                        ActivityUtils.showActivity(WebViewActivity.this, BloodOxygenActivity.class);
                    } else if (var.equals("9")) {
                        //跳到心电数据
                        ActivityUtils.showActivity(WebViewActivity.this, EcgHistoryActivity.class);
                    }
                } else if (url.contains("nfau://OPEN_6_")) {//电商+id

                    showToast("电商" + url.replaceAll("nfau://OPEN_6_", "") + "待接口");

                } else if (url.contains("nfau://OPEN_7_")) {//添加方案+id

                    Bundle bundle = new Bundle();
                    bundle.putString("schemetempletid", url.replaceAll("nfau://OPEN_7_", ""));//everydaynum
                    ActivityUtils.showActivity(WebViewActivity.this, HealthSchemeActivity.class, bundle);

                    showToast("添加方案" + url.replaceAll("nfau://OPEN_7_", ""));
                }
//                else if(url.contains("nfau://OPEN_8_")) {//我的方案+id
//
//                    showToast("我的方案" + url.replaceAll("nfau://OPEN_8_", ""));
//
//
//                }
                else if (url.contains("nfau://OPEN_9_")) {//我的私人医生+id
                    Bundle bundle = new Bundle();
                    bundle.putString(DocDetailActivity.DOCTORID, url.replaceAll("nfau://OPEN_9_", ""));
                    ActivityUtils.showActivity(WebViewActivity.this, DocDetailActivity.class, bundle);

                } else if (url.contains("nfau://OPEN_10_")) {//我的健康助手+id

                    Bundle bundle = new Bundle();
                    bundle.putString("doctorId", url.replaceAll("nfau://OPEN_10_", ""));


                } else if (url.contains("nfau://OPEN_11_")) {//我的健康银行+id

                    Bundle bundle = new Bundle();
                    bundle.putString(MyHealthBankDetailActivity.DOCTOR_ID, url.replaceAll("nfau://OPEN_11_", ""));
                    ActivityUtils.showActivity(WebViewActivity.this, MyHealthBankDetailActivity.class, bundle);

                }
//                else if(url.contains("nfau://OPEN_12_")) {//我的积分+id
//
//                    showToast("我的积分"+url.replaceAll("nfau://OPEN_12_",""));
//
//                }
//                else if(url.contains("nfau://OPEN_13_")) {//我的家人+id
//
//                    showToast("我的家人"+url.replaceAll("nfau://OPEN_13_",""));
//
//                }
                else if (url.contains("nfau://OPEN_14_")) {//我的医嘱+id

                    Bundle bundle = new Bundle();
                    bundle.putString(WebViewActivity.KEY_URL, Apis.HOST_COMMON + "/" + url.replaceAll("nfau://OPEN_14_", "") + "/index.html");
                    bundle.putString(WebViewActivity.KEY_TITLE, "检测报告");
                    ActivityUtils.showActivity(WebViewActivity.this, WebViewActivity.class, bundle);

                }else{
                    return super.shouldOverrideUrlLoading(view, getAddPalatformUrl(url));//（步骤三）
                }
//                else if(url.contains("nfau://OPEN_15_")) {//意见反馈+id
//                showToast("意见反馈"+url.replaceAll("nfau://OPEN_15_",""));
//                }
                /*else {
                   webview.loadUrl(url+ Apis.WEBVIEW_PLETEFORM);
                }*/
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                showLoading();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                hideLoading();
            }
        });


        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (TextUtils.isEmpty(WebViewActivity.this.title)) {
                    ViewUtil.setText(WebViewActivity.this, R.id.titlebar_title_tv, title);
                } else {
                    ViewUtil.setText(WebViewActivity.this, R.id.titlebar_title_tv, WebViewActivity.this.title);
                }
            }
        });
        String newStringUrl = getAddPalatformUrl(httpUrl);
        if(TextUtils.isEmpty(newStringUrl)){
            return ;
        }
        webview.loadUrl(newStringUrl);

        titlebar_right_view = ViewUtil.getView(this, R.id.titlebar_right_view);
        bm = BitmapFactory.decodeResource(getResources(), R.drawable.iconfont_share);
        titlebar_right_view.setOnClickListener(this);
        titlebar_right_view.setImageBitmap(bm);

        if (!isshare) {
            titlebar_right_view.setVisibility(View.GONE);
        } else {
            titlebar_right_view.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        webview.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        webview.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titlebar_right_view:

                CustomShareBoard shareBoard = new CustomShareBoard(WebViewActivity.this);
                shareBoard.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
                //再设置模式，和Activity的一样，覆盖，调整大小。
                shareBoard.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                shareBoard.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
                shareBoard.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
                //TODO
//                showBottomDialog();

                // 配置需要分享的相关平台
                configPlatforms();
                // 设置分享的内容
                setShareContent();
                break;
            case R.id.titlebar_back_view:
                if (webview.canGoBack()) {
                    webview.goBack();
                } else {
                    finish();
                }
                break;
            default:
                break;
        }
    }


    @SuppressLint("NewApi")
    private void showBottomDialog() {
        reportArr = new String[]{"", "分享"};
        new BottomSslideDialog(WebViewActivity.this, true, null, reportArr, new DialogOnitem() {
            @Override
            public void onItemClickListener(int position) {
                switch (position) {
                    case 0:
                        break;
                    default:
                        break;
                }

            }
        }).create();
    }

    private void onCollection() {//收藏监听
        // TODO Auto-generated method stub

        provider.CollectAdd(docid, title, imgurl, content, "CollectAdd");
    }

    @Override
    public void onBackPressed() {
        if (webview.canGoBack()) {
            webview.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (actionName.equals("CollectAdd")) {
            //			AdviceBanner result = (AdviceBanner) object;

            showToast("收藏成功");
            isstore = true;
        } else if (actionName.equals("ifCollection")) {
            //			AdviceBanner result = (AdviceBanner) object;
            if (object.toString().contains("true")) {
                isstore = true;
            } else {
                titlebar_right_view.setImageBitmap(bm);
                isstore = false;
            }
        } else if (actionName.equals("Delete_Collection")) {
            showToast("取消收藏成功！");
            isstore = false;
            titlebar_right_view.setImageBitmap(bm);
        } else if (actionName.equals("score")) {
            String msg = object + "";
            if (msg.contains("成功"))
                showToast("添加积分成功");
        }
    }

    public void clickOnAndroid(String id, final String time) {        // 注意这里的名称。它为clickOnAndroid(),注意，注意，严重注意
        this.id = id;
        this.time = time;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        mController.getConfig().cleanListeners();
        super.onDestroy();
    }

    private String getAddPalatformUrl(String httpUrl){
        String newStringUrl = "";
        if(!TextUtils.isEmpty(httpUrl)){
            if(httpUrl.endsWith("?") ){//以？结尾
                String  endWith= Apis.WEBVIEW_PLETEFORM.replace("&","");
                newStringUrl = httpUrl+ endWith;
            }else if(httpUrl.endsWith("/")){// 以/结尾
                httpUrl = httpUrl.substring(0,httpUrl.length()-1);
                String  endWith= Apis.WEBVIEW_PLETEFORM.replace("&","");
                newStringUrl = httpUrl+"?"+ endWith;
            }else if(httpUrl.contains("?") && !httpUrl.endsWith("?")){//中间包含？
                newStringUrl = httpUrl+ Apis.WEBVIEW_PLETEFORM;
            }else{//普通的网址-》字符串
                String  endWith= Apis.WEBVIEW_PLETEFORM.replace("&","");
                newStringUrl = httpUrl+"?"+ endWith;
            }
        }
        return newStringUrl;
    }
}
